<template>
  <div>
    <!-- 弹出抽屉-->
    <div>
      <t-drawer
        header="高级"
        attach="body"
        mode="push"
        :showOverlay="false"
        :visible.sync="drawerVisible"
        size="30%"
        placement="left"
        :closeBtn="true"
        sizeDraggable>
        <filter-menu></filter-menu>
        <template #footer>
          <div class="m-flex-row m-flex-row--right">
            <t-button @click="confirmFilterOption">确定</t-button>
          </div>
        </template>
      </t-drawer>
    </div>
    <!-- 搜索主页面-->
    <div class="home-container m-flex-col m-flex-col--top">
      <div class="title-container m-flex-col m-flex-col--top">
        <div class="main-title-block m-flex-row m-flex-row--center">
          <img class="main-logo" src="../assets/logo.png" />
          <div class="main-title-text">Chihiro 「 千寻 」</div>
        </div>
        <div class="sub-title-text">
          Search YICHE Code Source in the Chihiro Platform
        </div>
      </div>
      <div class="search-container m-flex-row m-flex-row--center">
        <div class="input-dropdown">
          <t-dropdown
            :options="dropdownOptions"
            trigger="click"
            @click="selectBranch"
            :maxColumnWidth="200"
            :maxHeight="200">
            <t-button
              theme="default"
              size="large"
              style="border-radius: 3px 0 0 3px"
              >{{ dropdownContent }}
            </t-button>
          </t-dropdown>
          <t-input
            style="border-radius: 0 3px 3px 0"
            v-model="searchStr"
            clearable
            placeholder="请输入内容"
            @enter="searchCode"
            size="large" />
        </div>
        <t-button
          theme="primary"
          size="large"
          class="search-btn"
          @click="searchCode"
          >搜索
        </t-button>
        <t-button
          theme="default"
          size="large"
          class="search-btn"
          @click="openFilterDrawer"
          >高级
        </t-button>
      </div>
      <!--搜索结果-->
      <div
        v-if="isHasSearchRes"
        id="search-resulte-container"
        class="filter-option-container">
        <t-collapse
          v-if="searchResList.length !== 0"
          :expand-icon="true"
          :expand-on-row-click="true"
          expandIconPlacement="right">
          <t-collapse-panel
            v-for="(repoItem, index) in searchResList"
            :key="index">
            <template #header>
              <div class="m-flex-row" style="width: 100%">
                <div>
                  <icon
                    name="control-platform"
                    size="large"
                    style="color: #006de3; margin-right: 10px" />
                  <span class="repo-name-title"
                    >{{ repoItem.repoName }} (匹配到{{
                      repoItem.matches.length
                    }}个文件，包含{{ repoItem.filesWithMatch }}个结果)</span
                  >
                </div>
                <div>{{ getCurRepoBelongTo(repoItem.repoName) }}</div>
              </div>
            </template>
            <template #default>
              <search-resulte-item
                style="margin: 20px 0"
                v-for="(fileItem, index) in repoItem.matches"
                :key="index"
                :fileItemInfo="fileItem"
                :repoItemInfo="repoItem"
                :RepoLink="gitLabJumpUrl(fileItem, repoItem.repoName)"
                >{{ index }}
              </search-resulte-item>
            </template>
          </t-collapse-panel>
        </t-collapse>
      </div>
      <div v-else>暂无查询结果</div>
      <t-loading
        class="search-loading"
        attach="#search-resulte-container"
        size="middle"
        text="努力加载中..."
        :loading="loading"></t-loading>
    </div>
    <!-- 回到顶部 -->
    <back-top></back-top>
  </div>
</template>

<script>
import { Icon } from "tdesign-icons-vue";
import FilterMenu from "@/components/FilterMenuV2";
import SearchResulteItem from "@/components/SearchResulteItem";
import BackTop from "@/components/BackTop";
import { searchCode } from "@/api/searchCode";
import { getAllbranch, getRepoInfoList } from "@/api/searchAllRepos";

export default {
  name: "Home",
  components: {
    Icon,
    FilterMenu,
    SearchResulteItem,
    BackTop,
  },
  data() {
    return {
      searchStr: "",
      drawerVisible: false,
      searchResList: [],
      loading: false,

      showArrow: true,
      direction: "left",
      disable: false,
      onlyIcon: false,

      isHasSearchRes: true,

      dropdownOptions: [],
      dropdownContent: "全部",
      dropdownSelectBranchId: "",

      repoStr: "*",

      allAdminRepoInfoList: [],
    };
  },
  computed: {
    // 为了在搜索结果中获得对应的文件gitlab仓库地址
    allRepos: {
      get() {
        return this.$store.state.siderFilter.allRepos;
      },
      set(v) {
        this.$store.commit("addAllRepos", v);
      },
    },
  },
  created() {
    this.getAllbranch();
    this.getRepoInfoList();
  },
  methods: {
    // 获取当前搜索结果的gitlab地址
    gitLabJumpUrl(fileItem, keyName) {
      return this.allRepos[keyName]?.url?.split(".git")[0];
    },
    getCurRepoBelongTo(repoName) {
      const curRepoInfo = this.allAdminRepoInfoList.filter((item) => {
        return item.gitlab_name === repoName;
      })?.[0];
      return `${curRepoInfo.branch_name}/${curRepoInfo.group_name}`;
    },
    searchCode(params) {
      const { isShortcut = false } = params;
      if (isShortcut === false && this.searchStr.trim() === "") {
        this.$message.warning("搜索关键词不能为空");
        return;
      }
      if (isShortcut === true) {
        this.searchStr = ``;
      }
      this.drawerVisible = false;

      this.loading = true;
      this.isHasSearchRes = true;
      this.searchResList = [];

      let includePath = this.$store.state.siderFilter.includePath;
      let excludePath = this.$store.state.siderFilter.excludePath;
      searchCode({
        branchId: this.dropdownSelectBranchId,
        q: this.searchStr.trim(),
        repos: this.repoStr,
        files: includePath,
        excludeFiles: excludePath,
      })
        .then((res) => {
          console.log("res --> ", res);
          // res结构
          // {
          //   Results:{
          //     仓库名:{
          //       FilesWithMatch:这个仓库匹配的结果数
          //       Matches：[
          //         {
          //           Filename: 文件名
          //           Matches:{
          //             Before:[],一个元素是一行的内容。为空代表和上一个是连在一起的
          //             After:[],一个元素是一行的内容
          //             Line:匹配的行的内容
          //             LineNumber:匹配的行号
          //           }
          //         }
          //       ]
          //       Revision：本次提交的hash值
          //     }
          //   },
          //   Stats:{
          //      Duration 搜索时间（毫秒）
          //      FilesOpened: 检索到的文件
          //   }
          // }
          const { Results } = res;
          const searchRepoNameResList = Object.keys(Results);

          const resList = [];
          if (searchRepoNameResList.length !== 0) {
            this.isHasSearchRes = true;
            searchRepoNameResList.forEach((repoName) => {
              const { FilesWithMatch, Matches, Revision } = Results[repoName];
              resList.push({
                repoName: repoName,
                filesWithMatch: FilesWithMatch,
                matches: Matches,
                revision: Revision,
              });
            });
            console.log("处理后的搜索结果", resList);
            this.searchResList = resList;
          } else {
            //搜索不到结果
            this.isHasSearchRes = false;
          }
        })
        .catch(() => {
          this.isHasSearchRes = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    async getAllbranch() {
      const res = await getAllbranch();
      if (res?.code === 0 && res?.data?.teams) {
        this.dropdownOptions = res.data.teams.map((item) => ({
          content: item.branch_name,
          value: item.id,
        }));
      }
    },
    async getRepoInfoList() {
      const res = await getRepoInfoList();
      if (res?.code === 0 && res?.data?.reposList) {
        this.allAdminRepoInfoList = res.data.reposList;
      }
    },
    openFilterDrawer() {
      this.drawerVisible = !this.drawerVisible;
    },
    confirmFilterOption() {
      this.drawerVisible = false;
    },
    async selectBranch(e) {
      this.dropdownContent = e.content;
      this.dropdownSelectBranchId = e.value;
    },
  },
};
</script>

<style lang="scss">
.input-dropdown {
  display: flex;
  align-items: center;
}
.home-container {
  width: 100%;
  min-height: 100vh;
  padding-top: 100px;
  background-color: #f9fafb;

  .title-container {
    width: 100%;

    .main-title-block {
      .main-logo {
        width: 50px;
        height: 50px;
        margin-right: 10px;
      }

      .main-title-text {
        font-size: 50px;
        font-weight: bold;
      }
    }

    .sub-title-text {
      font-font: 20px;
      color: #d1cdcd;
    }
  }

  .search-container {
    width: 100vw;
    margin: 20px 0;
    top: 0;
    .input-dropdown {
      width: 45%;
    }
    .search-btn {
      margin-left: 10px;
    }
  }
  .filter-option-container {
    width: 80%;
    position: relative;
    background-color: #f9fafb;
    .repo-name-title {
      font-weight: bold;
      font-size: 15px;
    }
  }
  .search-loading {
    padding-top: 100px;
  }
}
#search-resulte-container .t-loading--center {
  align-items: flex-start;
}

::v-deep .t-collapse-panel__body {
  background: #ffffff !important;
}
</style>
